package com.motong.gongdan.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.entity.LampType;
import com.motong.gongdan.entity.LampTypeNotice;
import com.motong.gongdan.mapper.LampTypeMapper;
import com.motong.gongdan.vo.system.LampType.query.LampTypeListQuery;
import com.motong.gongdan.vo.system.LampType.vo.LampTypeListVo;
import com.motong.gongdan.vo.system.common.vo.CheckBox;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LampTypeService extends ServiceImpl<LampTypeMapper, LampType> {

    @Resource
    private LampTypeMapper lampTypeMapper;

    @Resource
    private LampTypeNoticeService lampTypeNoticeService;

    /**
     * @param query 请求条件
     * @return 列表数据
     */
    public Page<LampTypeListVo> getList(LampTypeListQuery query) {
        Page<LampTypeListVo> data = lampTypeMapper.getList(new Page<>(query.getPage(), query.getLimit()), query);
        // 获取详情数据
        if (!CollectionUtils.isEmpty(data.getRecords())) {
            Set<Long> LampTypeIds = data.getRecords().stream().map(LampTypeListVo::getId).collect(Collectors.toSet());
            List<LampTypeNotice> detailData = lampTypeNoticeService.listByLampTypeIds(LampTypeIds);
            Map<Long, List<LampTypeNotice>> typeIdDataMap = Optional.ofNullable(detailData.stream().collect(Collectors.groupingBy(LampTypeNotice::getLampTypeId))).orElse(Collections.emptyMap());
            data.getRecords().forEach(i -> {
                i.setLampTypeNotices(typeIdDataMap.get(i.getId()));
                if (StringUtils.hasLength(i.getNoticeUserNames())) {
                    Set<String> repeatNames = new HashSet<>(Arrays.asList(i.getNoticeUserNames().split(",")));
                    i.setNoticeUserNames(null);
                    repeatNames.forEach(d -> {
                        i.setNoticeUserNames(Objects.nonNull(i.getNoticeUserNames()) ? i.getNoticeUserNames().concat(",").concat(d) : d);
                    });
                }
            });
        }
        return data;
    }


    /**
     * @param query 请求条件
     * @return 下拉列表
     */
    public List<CheckBox> dropDown(LampTypeListQuery query) {
        return lampTypeMapper.dropDown(query);
    }
}
